package org.dromara.hm.service.impl;

/**
 * @Author If404 Hzy
 * @Date 2025-2025/6/13-10:37
 * @Version 1.0
 */
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.RequiredArgsConstructor;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.DateUtils;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.hm.domain.HmCustomer;
import org.dromara.hm.domain.HmCustomerTransferHistory;
import org.dromara.hm.domain.HmOrderTransferHistory;
import org.dromara.hm.domain.HmSaleOrder;
import org.dromara.hm.domain.HmTodoItems;
import org.dromara.hm.domain.HmTodoTransferHistory;
import org.dromara.hm.mapper.HmCustomerMapper;
import org.dromara.hm.mapper.HmCustomerTransferHistoryMapper;
import org.dromara.hm.mapper.HmOrderTransferHistoryMapper;
import org.dromara.hm.mapper.saleOrder.HmSaleOrderMapper;
import org.dromara.hm.mapper.HmTodoItemsMapper;
import org.dromara.hm.mapper.HmTodoTransferHistoryMapper;
import org.dromara.hm.service.ITransferRevertService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;

@RequiredArgsConstructor
@Service
public class TransferRevertServiceImpl implements ITransferRevertService
{

    private final HmCustomerMapper customerMapper;
    private final HmSaleOrderMapper saleOrderMapper;
    private final HmTodoItemsMapper todoItemsMapper;
    private final HmCustomerTransferHistoryMapper customerHistoryMapper;
    private final HmOrderTransferHistoryMapper orderHistoryMapper;
    private final HmTodoTransferHistoryMapper todoHistoryMapper;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void revertBatch(Long customerHistoryId) {
        // Revert customer
        long oldStaffId = revertCustomer(customerHistoryId);

        // Find and revert related orders
        List<HmOrderTransferHistory> orderHistories = orderHistoryMapper.selectList(
            new LambdaQueryWrapper<HmOrderTransferHistory>()
                .eq(HmOrderTransferHistory::getCustomerTransferHistoryId, customerHistoryId)
                .eq(HmOrderTransferHistory::getStatus, "0")
        );
        for (HmOrderTransferHistory history : orderHistories) {
            revertOrder(history.getOrderTransferHistoryId());
        }

        // 待办与老员工有关,与客户无关
        List<HmTodoTransferHistory> todoHistories = todoHistoryMapper.selectList(
            new LambdaQueryWrapper<HmTodoTransferHistory>()
                .eq(HmTodoTransferHistory::getOldTodoPersonId, oldStaffId)
                .eq(HmTodoTransferHistory::getStatus, "0")
        );
        for (HmTodoTransferHistory history : todoHistories) {
            revertTodo(history.getTodoTransferHistoryId());
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public long revertCustomer(Long customerHistoryId) {
        HmCustomerTransferHistory history = customerHistoryMapper.selectById(customerHistoryId);
        if (history == null) throw new ServiceException("客户转移记录不存在");
        if ("1".equals(history.getStatus())) throw new ServiceException("该客户转移记录已撤销，请勿重复操作");

        HmCustomer customer = customerMapper.selectById(history.getCustomerId());
        if (customer == null) throw new ServiceException("关联的客户不存在，无法撤销");

        // Update customer back to old state
        customer.setStaffId(history.getOldStaffId());
        customer.setStaffName(history.getOldStaffName());
        customer.setStoreId(history.getOldStoreId());
        customer.setStoreName(history.getOldStoreName());
        customer.setUpdateBy(LoginHelper.getUserId());
        customer.setUpdateTime(DateUtils.getNowDate());
        customerMapper.updateById(customer);

        // Mark history as reverted
        history.setStatus("1");
        customerHistoryMapper.updateById(history);
        return history.getOldStaffId();
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void revertOrder(Long orderHistoryId) {
        HmOrderTransferHistory history = orderHistoryMapper.selectById(orderHistoryId);
        if (history == null) throw new ServiceException("订单转移记录不存在");
        if ("1".equals(history.getStatus())) throw new ServiceException("该订单转移记录已撤销，请勿重复操作");

        HmSaleOrder order = saleOrderMapper.selectById(history.getSaleOrderId());
        if(order == null) throw new ServiceException("关联的订单不存在，无法撤销");

        // Update order back to old state
        order.setSaleUser(history.getOldSaleUser());
        order.setSaleUserName(history.getOldSaleUserName());
        order.setSaleDept(history.getOldSaleDept());
//        order.setSaleDeptName(history.getOldSaleDeptName());
        order.setUpdateBy(LoginHelper.getUserId());
        order.setUpdateTime(DateUtils.getNowDate());
        saleOrderMapper.updateById(order);

        // Mark history as reverted
        history.setStatus("1");
        orderHistoryMapper.updateById(history);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void revertTodo(Long todoHistoryId) {
        HmTodoTransferHistory history = todoHistoryMapper.selectById(todoHistoryId);
        if (history == null) throw new ServiceException("待办转移记录不存在");
        if ("1".equals(history.getStatus())) throw new ServiceException("该待办转移记录已撤销，请勿重复操作");

        HmTodoItems todo = todoItemsMapper.selectById(history.getTodoId());
        if (todo == null) throw new ServiceException("关联的待办不存在，无法撤销");

        // Update todo back to old state
        todo.setTodoPersonId(history.getOldTodoPersonId());
        todo.setTodoPersonName(history.getOldTodoPersonName());
        todo.setUpdateBy(LoginHelper.getUserId());
        todo.setUpdateTime(DateUtils.getNowDate());
        todoItemsMapper.updateById(todo);

        // Mark history as reverted
        history.setStatus("1");
        todoHistoryMapper.updateById(history);
    }
}
